﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace CommunitySystem
{
    public partial class CandidatorCheckWindow : ChildWindow
    {
        private JinShengService.JinShen_MainInfo _MainInfo = null;

        private JinShengService.JinShen_CompetSpeech_Main SpeechMain = null;

        private JinShengService.JinShen_Democraticevaluation_Main EvaMain = null;

        private PublicOfficialSelectionService.PublicOfficialSelectionServiceClient _uploadClient = null;

        private JinShengService.JinShengServiceClient _Client = null;

        public CandidatorCheckWindow(JinShengService.JinShen_MainInfo MainInfo)
        {
            InitializeComponent();
            _uploadClient = new PublicOfficialSelectionService.PublicOfficialSelectionServiceClient();
            _Client = new JinShengService.JinShengServiceClient();
            _uploadClient.UploadFileCompleted += new EventHandler<PublicOfficialSelectionService.UploadFileCompletedEventArgs>(_uploadClient_UploadFileCompleted);
            _MainInfo = MainInfo;
            if (_MainInfo.Status.Equals(CommunitySystem.PageView.JinShenConst.STATUS_CandidateCheck_Pass))//新增
            {
                if(_MainInfo.PromotType.Equals("竞争上岗"))
                    SpeechMain = new JinShengService.JinShen_CompetSpeech_Main() { MainID= _MainInfo.ID, CreateDay = DateTime.Now, CreateUser= EHR.Common.Session.LoginUser.LoginName, Details = new System.Collections.ObjectModel.ObservableCollection<JinShengService.JinShen_CompetSpeech_Detail>() };
                EvaMain = new JinShengService.JinShen_Democraticevaluation_Main() { MainID = _MainInfo.ID,  Details = new System.Collections.ObjectModel.ObservableCollection<JinShengService.JinShen_Democraticevaluation_Detail>() };
                foreach (var d in _MainInfo.Details)
                {
                    if (SpeechMain != null)
                    {
                        JinShengService.JinShen_CompetSpeech_Detail detail = new JinShengService.JinShen_CompetSpeech_Detail() { EmpID = d.EmpBasicID, EmpName = d.Name };
                        SpeechMain.Details.Add(detail);
                    }
                    JinShengService.JinShen_Democraticevaluation_Detail detail1 = new JinShengService.JinShen_Democraticevaluation_Detail() { EmpID = d.EmpBasicID, EmpName = d.Name };
                    
                    EvaMain.Details.Add(detail1);
                }
                DataBinding();
            }
            else//编辑审核
            {
                _Client.GetDemocraEvalutionCompleted += (sender, e) =>
                {
                    EvaMain = e.Result.LastOrDefault();
                    if (_MainInfo.PromotType.Equals("竞争上岗"))
                    {
                        _Client.GetCompetSpeechMainAsync("MainID="+_MainInfo.ID);
                    }
                    else
                    {
                        DataBinding();
                    }
                };

                _Client.GetCompetSpeechMainCompleted += (sender, e) =>
                {
                    SpeechMain = e.Result.LastOrDefault();
                    DataBinding();
                };

                _Client.GetDemocraEvalutionAsync("MainID=" + _MainInfo.ID);
            }

            _Client.SaveDetailCheckCompleted += (sender, e) =>
            {
                if (e.Error == null && e.Result == true)
                {
                    SilverlightMessageBoxLibrary.Message.InfoMessage("保存成功");
                    this.DialogResult = true;
                }
                else
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("保存失败");
                }
            };

           
        }

        private readonly string fileDictionary = "file";

        void _uploadClient_UploadFileCompleted(object sender, PublicOfficialSelectionService.UploadFileCompletedEventArgs e)
        {
            var file = e.UserState as UploadFileInfo;
            if (file.Context.Count > 0)
            {
                _uploadClient.UploadFileAsync(fileDictionary, file.DisplayName, file.Context[0], false, file);
                file.Context.RemoveAt(0);
            }
            else
            {
                if (files.Values.LastOrDefault() == file)
                {
                    _Client.SaveDetailCheckAsync(EvaMain, SpeechMain, _MainInfo);                    
                }
            }
        }

        private Dictionary<string, UploadFileInfo> files = new Dictionary<string, UploadFileInfo>();

        private void DataBinding()
        {
            //EvaMain.PropertyChanged += (sender1, e1) =>
            //{
            //    if (e1.PropertyName.Equals("GiveUpCount"))
            //    {
            //        try
            //        {
            //            var detail = sender1 as JinShengService.JinShen_Democraticevaluation_Detail;
            //            int count = (int)detail.AgreeCount + (int)detail.DisAgreeCount + (int)detail.GiveUpCount;
            //            if (count > 0)
            //            {
            //                var rate = (int)detail.DisAgreeCount * 100.0 / count;
            //                detail.UnAgreeRate =  (decimal)Math.Round(rate, 2);
            //            }
            //        }
            //        catch (Exception)
            //        {
            //        }
            //    }
            //};
            if (_MainInfo.PromotType != "竞争上岗")
            {
                LayoutRoot.RowDefinitions[1].Height = new GridLength(0);
                GridSpeech.Height = 0;
                this.Height = 360;
            }
            else
            {
                GridSpeech.DataContext = SpeechMain;
                foreach (var d in SpeechMain.Details)
                {                
                    StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal, DataContext = d,  Margin= new Thickness(5) };
                    TextBlock tb = new TextBlock() { Text = d.EmpName, Width= 35, Margin= new Thickness(3) };
                    sp.Children.Add(tb);
                    //TextBox tbox = new TextBox() { Margin = new Thickness(5, 0, 0, 0), MinWidth=120 };
                    //tbox.SetBinding(TextBox.TextProperty, new System.Windows.Data.Binding("Decription") { Mode = System.Windows.Data.BindingMode.TwoWay });
                    //sp.Children.Add(tbox);
                    if (!string.IsNullOrEmpty(d.realName))
                    {
                        StackPanel sp1 = new StackPanel() { Orientation = Orientation.Horizontal, Margin = new Thickness(5, 0, 0, 0) };
                        sp1.Children.Add(new TextBlock() { Text = d.realName, });
                        Image img = new Image() { Cursor = Cursors.Hand, Height = 15, Width = 15, Margin = new Thickness(5, 0, 0, 0) };
                        img.Source = new System.Windows.Media.Imaging.BitmapImage(
                            new Uri("/CommunitySystem;component/Images/ViewDesign/delete.png",
                                UriKind.RelativeOrAbsolute));
                        sp1.Children.Add(img);
                        img.MouseLeftButtonDown += (sender1, e1) =>
                        {
                            d.GuidName = "";
                            d.realName = "";
                            sp.Children.Remove(sp1);

                        };
                        sp.Children.Insert(1, sp1);
                    }
                    HyperlinkButton hlb = new HyperlinkButton() { Content = "上传竞争上岗演讲内容", Margin = new Thickness(5, 0, 0, 0), DataContext = d };                    
                    hlb.Click += (sender, e) =>
                    {
                        var openFile = new OpenFileDialog() { Multiselect = false };
                        if (openFile.ShowDialog() == true)
                        {
                            string GuidName = Guid.NewGuid().ToString("N");
                            CommunitySystem.JinShengService.JinShen_CompetSpeech_Detail detail = (sender as HyperlinkButton).DataContext as CommunitySystem.JinShengService.JinShen_CompetSpeech_Detail;
                            UploadFileInfo uploadFile = new UploadFileInfo() { DisplayName = GuidName, Name = GuidName };
                            var stream = openFile.File.OpenRead();
                            uploadFile.Size = stream.Length / 16000;
                            uploadFile.Context = new List<byte[]>();
                            int b = 0;
                            while (stream.Position > -1 && stream.Position < stream.Length)
                            {
                                if (stream.Length - stream.Position >= 16000)
                                {
                                    b = 16000;
                                }
                                else
                                {
                                    b = (int)(stream.Length - stream.Position);
                                }

                                byte[] filebyte = new byte[b];
                                stream.Read(filebyte, 0, b);
                                uploadFile.Context.Add(filebyte);
                            }
                            stream.Close();
                            files.Add(GuidName, uploadFile);
                            detail.GuidName = GuidName;
                            detail.realName = openFile.File.Name;
                            StackPanel sp1 = new StackPanel() { Orientation = Orientation.Horizontal, Margin = new Thickness(5, 0, 0, 0) };
                            sp1.Children.Add(new TextBlock() { Text = openFile.File.Name, });
                            Image img = new Image() { Cursor = Cursors.Hand, Height = 15, Width = 15, Margin = new Thickness(5, 0, 0, 0) };
                            img.Source = new System.Windows.Media.Imaging.BitmapImage(
                                new Uri("/CommunitySystem;component/Images/ViewDesign/delete.png",
                                    UriKind.RelativeOrAbsolute));
                            sp1.Children.Add(img);

                            img.MouseLeftButtonDown += (sender1, e1) =>
                            {
                                
                                files.Remove(GuidName);
                                detail.GuidName = "";
                                detail.realName = "";
                                sp.Children.Remove(sp1);

                            };
                            if (sp.Children.Count > 2)
                                sp.Children.RemoveAt(1);

                            sp.Children.Insert(1, sp1);

                            //wp.Children.Add(sp);

                        }
                    };
                    sp.Children.Add(hlb);
                    svDetails.Children.Add(sp);
                }
            }
            GridEvalution.DataContext = EvaMain;
            foreach (var d in EvaMain.Details)
            {
                d.PropertyChanged += (sender1, e1) =>
                {
                    if (e1.PropertyName.Equals("GiveUpCount") || e1.PropertyName.Equals("AgreeCount") || e1.PropertyName.Equals("DisAgreeCount"))
                    {
                        try
                        {
                            var detail = sender1 as JinShengService.JinShen_Democraticevaluation_Detail;
                            int count = (int)detail.AgreeCount + (int)detail.DisAgreeCount + (int)detail.GiveUpCount;
                            if (count > 0)
                            {
                                var rate = (int)detail.DisAgreeCount * 100.0 / count;
                                detail.UnAgreeRate = (decimal)Math.Round(rate, 2);
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                };
                StackPanel sp = new StackPanel() { Orientation = Orientation.Horizontal, DataContext = d, Margin= new Thickness(5) };
                TextBlock tb = new TextBlock() { Text = d.EmpName + ":", Width = 35, Margin = new Thickness(3) };
                sp.Children.Add(tb);
                tb = new TextBlock() { Text = "同意", Margin = new Thickness(3) };
                sp.Children.Add(tb);
                TextBox tbox = new TextBox() { Margin = new Thickness(5, 0, 0, 0), Width=30 };
                tbox.SetBinding(TextBox.TextProperty, new System.Windows.Data.Binding("AgreeCount") { Mode = System.Windows.Data.BindingMode.TwoWay });
                sp.Children.Add(tbox);


                tb = new TextBlock() { Text = "票, 不同意", Margin = new Thickness(3) };
                sp.Children.Add(tb);
                tbox = new TextBox() { Margin = new Thickness(5, 0, 0, 0), Width = 30 };
                tbox.SetBinding(TextBox.TextProperty, new System.Windows.Data.Binding("DisAgreeCount") { Mode = System.Windows.Data.BindingMode.TwoWay });
                sp.Children.Add(tbox);

                tb = new TextBlock() { Text = "票, 弃权", Margin = new Thickness(3) };
                sp.Children.Add(tb);
                tbox = new TextBox() { Margin = new Thickness(5, 0, 0, 0), Width = 30 };
                tbox.SetBinding(TextBox.TextProperty, new System.Windows.Data.Binding("GiveUpCount") { Mode = System.Windows.Data.BindingMode.TwoWay });
                sp.Children.Add(tbox);
                tb = new TextBlock() { Text = "票。", Margin = new Thickness(3) };
                sp.Children.Add(tb);



                tb = new TextBlock() { Text = "  不同意率:", Margin = new Thickness(3) };
                sp.Children.Add(tb);
                tbox = new TextBox() { Margin = new Thickness(5, 0, 0, 0), Width = 40, IsReadOnly= true };
                tbox.SetBinding(TextBox.TextProperty, new System.Windows.Data.Binding("UnAgreeRate") { Mode = System.Windows.Data.BindingMode.TwoWay, StringFormat="{0:.00}"});
                sp.Children.Add(tbox);
                tb = new TextBlock() { Text = "%", Margin = new Thickness(3) };
                sp.Children.Add(tb);
                svDetails2.Children.Add(sp);
            }
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            if (Validate())
            {
                #region 上传文件
                _MainInfo.Status = CommunitySystem.PageView.JinShenConst.STATUS_Candidate_Approved;//"候选人审核中";
                if (files.Count > 0)//有附件上传
                {
                    foreach (var key in files.Keys)
                    {
                        var file = files[key];
                        _uploadClient.UploadFileAsync(fileDictionary, file.DisplayName, file.Context[0], true, file);
                        file.Context.RemoveAt(0);
                    }
                }
                else//没有附件
                {
                    _Client.SaveDetailCheckAsync(EvaMain, SpeechMain, _MainInfo);
                }
                #endregion
            }

        }

        /// <summary>
        /// 验证
        /// </summary>
        /// <returns></returns>
        private bool Validate()
        {
            #region 竞争上岗
            if (SpeechMain != null)
            {
                var detail = SpeechMain.Details.Where(c => string.IsNullOrEmpty(c.GuidName)).FirstOrDefault();
                if (detail != null)
                {
                    SilverlightMessageBoxLibrary.Message.ErrorMessage("请上传"+detail.EmpName+"的演讲附件!");
                    return false;
                }
                //if (string.IsNullOrEmpty(SpeechMain.Description))
                //{
                //    //SilverlightMessageBoxLibrary.Message.ErrorMessage("请填写描述信息!");
                //    //return false;
                //}
            }
            #endregion

            #region 民主测评
            if (EvaMain.TotalCount <= 0 || EvaMain.TotalCount == null)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("应参加评测人数填写错误!");
                return false;
            }
            if (EvaMain.Realcount <= 0 || EvaMain.Realcount == null)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("实到人数填写错误!");
                return false;
            }
            if (EvaMain.Realcount > EvaMain.TotalCount)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("实到人数不能大于应参加人数!");
                return false;
            }

            if (EvaMain.Realcount > EvaMain.TotalCount)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("实到人数不能大于应参加人数!");
                return false;
            }
            var de = EvaMain.Details.Where(c => c.AgreeCount < 0 || c.AgreeCount == null).FirstOrDefault();
            if (de != null)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage(de.EmpName + "的同意票数不能小于0");
                return false;
            }

            de = EvaMain.Details.Where(c => c.DisAgreeCount < 0 || c.DisAgreeCount == null).FirstOrDefault();
            if (de != null)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage(de.EmpName + "的不同意票数不能小于0");
                return false;
            }

            de = EvaMain.Details.Where(c => c.GiveUpCount < 0 || c.GiveUpCount == null).FirstOrDefault();
            if (de != null)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage(de.EmpName + "的弃权票数不能小于0");
                return false;
            }

            de = EvaMain.Details.Where(c => c.GiveUpCount + c.DisAgreeCount + c.AgreeCount >  EvaMain.Realcount).FirstOrDefault();
            if (de != null)
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage(de.EmpName + "的票数不能大于实到人数");
                return false;
            }

            #endregion
            return true;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }
    }
}

